//
//  Shader.metal
//  videoPlayer
//
//  Created by xwl on 2019/2/26.
//  Copyright © 2019年 xuwanliang. All rights reserved.
//

#include <metal_stdlib>
using namespace metal;

struct VertexIn {
    float2 position [[]];
    float2 m_TexCoord;
};
struct VertexOut {
    float4 position [[position]];
    float2 m_TexCoord;
};

struct ColorParameters
{
    float3x3 yuvToRGB;
};

vertex VertexOut vertex_func(constant VertexIn *vertices [[buffer(0)]],uint vid [[vertex_id]]){
    VertexIn vert = vertices[vid];
    VertexOut outVert;
    outVert.position = float4(vert.position, 0.0, 1.0);
    outVert.m_TexCoord = vert.m_TexCoord;
    return outVert;
}

fragment float4 fragment_func(VertexOut vert [[stage_in]],
                              texture2d<float, access::sample> colorTexture [[ texture(0) ]],
                              texture2d<float, access::sample> interTexture [[ texture(1) ]],
                              sampler colorSampler [[ sampler(0) ]]){
    float2 texCoor = vert.m_TexCoord;
    texCoor.x = vert.m_TexCoord.x * 0.5;
    float4 coll = colorTexture.sample(colorSampler, texCoor);
    texCoor.x += 0.5;
    float4 colr = colorTexture.sample(colorSampler, texCoor);
    
    float  sup = interTexture.sample(colorSampler, vert.m_TexCoord).r;
    float4 color = sup * coll + (1.0 - sup) * colr;
    
    uint cx = texCoor.x * 2868.0;
    
    if(cx % 2 == 0){
        color.r = 1.0;
        color.g = 0.0;
        color.b = 0.0;
    }else{
        color.r = 0.0;
        color.g = 0.0;
        color.b = 0.0;
    }
    
    return color;
}


fragment half4 yuv_rgb(VertexOut         inFrag         [[ stage_in ]],
                       texture2d<float>  lumaTex        [[ texture(0) ]],
                       texture2d<float>  chromaTex      [[ texture(1) ]],
                       sampler           bilinear       [[ sampler(0) ]],
                       constant ColorParameters *colorParameters [[ buffer(0) ]])
{
    float3 yuv;
    yuv.x = lumaTex.sample(bilinear, inFrag.m_TexCoord).r - 0.0706;
    yuv.yz = chromaTex.sample(bilinear,inFrag.m_TexCoord).rg - float2(0.5);

//    float3x3 cusyuv = float3x3(float3(1.0, 1.0, 1.0),
//                               float3(0.0, -0.343, 1.765),
//                               float3(1.4, -0.711, 0.0));
//    return half4(half3(cusyuv * yuv), 1.0);
    
    return half4(half3(colorParameters->yuvToRGB * yuv), 1.0);
}
